package cn.edu.hncst.controller;

import cn.edu.hncst.dao.UserDao;
import cn.edu.hncst.entity.User;
import cn.edu.hncst.service.UserService;
import cn.edu.hncst.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        req.setCharacterEncoding("utf-8");
        //初始化提示信息
        String msg = null;
        //获取用户输入的验证码
        String verifycode = req.getParameter("verifycode");

        //获取后台验证码
        String checkCode =  (String) req.getSession().getAttribute("CHECKCODE_SERVER");

        req.getSession().removeAttribute("CHECKCODE_SERVER");


        //获取用户名
        String username = req.getParameter("username");
        //获取密码
        String password = req.getParameter("password");
        //验证信息完整性
        if(username==""||password==""||verifycode==""){
            msg="请填写完整";
            req.setAttribute("login_msg",msg);
            req.getRequestDispatcher( "/login.jsp").forward(req,resp);
        }

        //多态
        UserService userService = new UserServiceImpl();
        //比对验证码
        if (verifycode.equalsIgnoreCase(checkCode)) {
            //查询用户是否为空
            User user = userService.findById(username, password);
            if (user != null) {
                HttpSession session = req.getSession(true);
                session.setAttribute("user",user);
                //跳转到首页
                req.setAttribute("user",user);
                req.getRequestDispatcher( "/index.jsp").forward(req,resp);
            }else{
                msg="用户名或密码错误";
                req.setAttribute("login_msg",msg);
                req.getRequestDispatcher( "/login.jsp").forward(req,resp);
            }

        }
        msg="验证码错误";
        req.setAttribute("login_msg",msg);
        req.getRequestDispatcher( "/login.jsp").forward(req,resp);
    }
}
